package cn.wolfcode.luowowo.resolver;


import cn.wolfcode.luowowo.annotation.UserParam;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.IUserRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户对象解析器
 * 将cookie中token值解析成UserInfo对象, 并注入到请求映射方法参数中
 */
@Component
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private IUserRedisService userRedisService;

    //该解析器支持解析的参数类型
    //此处支持的UserInfo类型
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果是true, 表示支持对应的类型, 如果为false表示不支持
        return parameter.getParameterType() == UserInfo.class
               && parameter.hasParameterAnnotation(UserParam.class);
    }

    //一旦这个upportsParameter返回true, 表示该解析器启动了, 需要解析对应的参数
    //解析器解析规则:
    // 此方法解析规则: 将 token 转换成 UserInfo对象
    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse resp = webRequest.getNativeResponse(HttpServletResponse.class);
        String token = req.getHeader("token");
        return userRedisService.getUserByToken(token);
    }
}
